<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use App\Models\OperationLog;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/materials';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * 显示登录页面
     */
    public function showLoginForm()
    {
        return view('auth.login');
    }

    /**
     * 处理登录请求
     */
    public function login(Request $request)
    {
        // 验证登录数据
        $credentials = $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
        ]);

        // 尝试登录
        if (Auth::attempt($credentials, $request->filled('remember'))) {
            $request->session()->regenerate();
            // 记录登录日志
            OperationLog::create([
                'user_id' => Auth::id(),
                'action' => 'login',
                'target_type' => 'user',
                'target_id' => Auth::id(),
                'content' => "用户登录",
                'ip' => $request->ip()
            ]);

            // 根据用户角色跳转到不同页面
//            if (Auth::user()->hasRole('admin')) {
//                return redirect()->route('materials.index');
//            } else {
                return redirect()->route('materials.index');
//            }
        }
        // 记录登录失败日志
        OperationLog::create([
            'user_id' => null,
            'action' => 'login_failed',
            'content' => '登录失败：用户名 ' . $request->username,
            'ip' => $request->ip()
        ]);

        return back()->withErrors([
            'username' => '用户名或密码错误',
        ]);
    }

    /**
     * 处理登出请求
     */
    public function logout(Request $request)
    {
        // 记录登出日志
        if (Auth::check()) {
            OperationLog::create([
                'user_id' => Auth::id(),
                'action' => 'logout',
                'target_type' => 'user',
                'target_id' => Auth::id(),
                'content' => "用户登出",
                'ip' => $request->ip()
            ]);
        }

        $this->guard()->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect('/');
    }

    protected function authenticated(Request $request, $user)
    {
        // 记录登录日志
        OperationLog::create([
            'user_id' => $user->id,
            'action' => 'login',
            'content' => '用户登录成功',
            'ip' => $request->ip()
        ]);

        // 根据用户角色决定跳转页面
        if ($user->hasRole('admin')) {
            return redirect()->route('dashboard');
        } else {
            return redirect()->route('materials.index');
        }
    }
}
